<template>
    <el-main>
        <el-button type="success" style="margin-bottom: 10px;" @click="open(null)">增加</el-button>
        <el-table :data="teee" border style="width: 1000px;height: 550px;">
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" width="55" label="序号" />
            <el-table-column prop="goodsId" label="生产名称" />
            <el-table-column prop="productionbatches" label="生产批次" />
            <el-table-column prop="shelflifeDay" label="保质期（天）" />
            <el-table-column prop="productionlicense" label="生产许可证" />
            <el-table-column prop="productionCompany" label="生产企业" />
            <el-table-column label="操作">
                <template v-slot="scope" style="width: 50px">
                    <el-button size="small" type="danger" @click="del(scope.row)">删除</el-button>
                    <el-button size="small" type="primary" @click="open(scope.row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="from.pageIndex" v-model:page-size="from.pageSize"
            :page-sizes="[10, 20, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="from.recordCount" />
    </el-main>
    <div>
        <el-dialog v-model="logic.isOpen" title="基本信息" width="500">
            <el-form :model="consid" width-label="200px">
                <el-form-item label="商品名称: ">
                    <el-input v-model="consid.goodsId" />
                </el-form-item>
                <el-form-item label="生产批次: ">
                    <el-input v-model="consid.productionbatches" />
                </el-form-item>
                <el-form-item label="保质期（天）: ">
                    <el-input v-model="consid.shelflifeDay" />
                </el-form-item>
                <el-form-item label="生产许可证号: ">
                    <el-input v-model="consid.productionlicense" />
                </el-form-item>
                <el-form-item label="生产企业: ">
                    <el-input v-model="consid.productionCompany" />
                </el-form-item>
                <el-form-item label="封面图: ">
                    <!--上传图片-->
                    <el-upload class="avatar-uploader"
                        action="http://localhost:62301/api/Trance/UploadImages/UploadImages" :show-file-list="true"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl.value" :src="imageUrl.value" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="logic.isOpen = false">取消</el-button>
                    <el-button type="primary" @click="addTrace()">
                        添加
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>


<script setup lang="ts">
import { reactive, ref, onMounted, watch, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCounterStore } from "@/stores/counter"
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
const router = useRouter()

//分页
const from = reactive({
    pageIndex: 1,
    pageSize: 10,
    recordCount: 1,
    pageCount: 1
})
//上传图片
const consid = reactive({
    trId: 0,
    goodsId: "",
    productionbatches: "",
    shelflifeDay: "",
    productionlicense: "",
    productionCompany: "",
    coverimage: "",
})
const logic = reactive({
    isOpen: false,
    isAdd: true
})
//上传图片
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    consid.coverimage = response;
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
//上传图片
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log('Before upload - File:', rawFile);
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!');
        return false;
    }
    return true;
};
//表格显示
const teee = ref([])
const Gettable = () => {
    axios.get("http://localhost:42960/api/User/TranceShow", {
        params: {
            pageIndex: from.pageIndex,
            pageSize: from.pageSize
        }
    }).then(res => {
        teee.value = res.data.data.list

        from.recordCount = res.data.data.recordCount
        from.pageCount = res.data.data.pageCount
    })
}
//添加
const addTrace = () => {
    if (consid.goodsId == "") {
        ElMessage.error("商品名称不能为空")
        return
    }
    if (consid.productionbatches == "") {
        ElMessage.error("生产批次不能为空")
        return
    }
    if (consid.shelflifeDay == "") {
        ElMessage.error("保质期不能为空")
        return
    }
    if (consid.productionlicense == "") {
        ElMessage.error("生产许可证号不能为空")
        return
    }
    if (consid.productionCompany == "") {
        ElMessage.error("生产企业不能为空")
        return
    }
    if (consid.coverimage == "") {
        ElMessage.error("封面图不能为空")
        return
    }
    axios.post("http://localhost:62301/api/Trance/AddTrance", consid).then(res => {
        if (res.data.code == 300) {
            ElMessage.success(res.data.message)
            logic.isOpen = false
            Gettable()
        }
        else {
            ElMessage.error(res.data.message)
            return
        }
    })
}

const open = (row: any) => {
    logic.isOpen = true
    if (row == null) {
        logic.isAdd = true

        consid.trId = 0
        consid.goodsId = "";
        consid.productionbatches = "";
        consid.shelflifeDay = "";
        consid.productionlicense = "";
        consid.productionCompany = "";
        consid.coverimage = "";
        imageUrl.value = ''; // 确保在增加模式下清除图片路径
    }
    else {
        logic.isAdd = false

        consid.trId = row.trId;
        consid.goodsId = row.goodsId;
        consid.productionbatches = row.productionbatches;
        consid.shelflifeDay = row.shelflifeDay;
        consid.productionlicense = row.productionlicense;
        consid.productionCompany = row.productionCompany;


        // 添加调试信息，确保 row.coverimage 的值正确
        console.log('Cover image URL:', row.coverimage);

        // 确保 imageUrl 设置为正确的图片 URL
        imageUrl.value = row.coverimage; // 如果 coverimage 是一个有效的 URL 或路径，这行代码应该可以工作
        router.push({
            name: 'Show1',
            params: {
                trId: row.trId
            }
        })
    }
}
//删除
const del = (row: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("http://localhost:62301/api/Trance/DelTrance", row).then(res => {
                if (res.data.code == 400) {
                    ElMessage.success(res.data.message)
                    Gettable()
                }
                else {
                    ElMessage.error(res.data.message)
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}

watch(from, () => {
    Gettable()
})

onMounted(() => {
    Gettable()
})
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>